<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规格名称" prop="ruleName">
        <el-input v-model="queryParams.ruleName" placeholder="请输入规格名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:storeProductRule:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:storeProductRule:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:storeProductRule:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:storeProductRule:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeProductRuleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="规格名称" align="center" prop="ruleName" />
      <el-table-column label="规格值" align="center" prop="ruleValue">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.ruleValue" :key="index">
            <span>{{ item.value }}：</span>
            <span v-for="(itm, inx) in item.detail" :key="inx" style="margin-right: 5px;">{{ itm }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:storeProductRule:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:storeProductRule:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品规则值(规格)对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="950px" append-to-body>
      <el-form ref="form" :model="formData" class="attrFrom" :rules="rules" label-width="92px" :inline="true">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-col :span="9" class="mb15">
              <el-form-item label="规格名称：" prop="ruleName">
                <el-input placeholder="请输入规格名称" v-model="formData.ruleName" />
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="23" class="noForm" v-for="(item, index) in formData.ruleValue" :key="index">
            <el-form-item label=" ">
              <div class="acea-row row-middle">
                <span class="mr5">{{ item.value }}</span>
                <i class="el-icon-circle-close" @click="handleRemove(index)"></i>
              </div>
              <div class="rulesBox">
                <el-tag class="mb5" style="margin: 2px 4px 2px 0" closable v-for="(j, indexn) in item.detail"
                  :key="indexn" :name="j" @close="handleRemove2(item.detail, indexn)">{{ j }}
                </el-tag>
                <el-input placeholder="请输入属性名称" v-model="item.detail.attrsVal" style="width: 170px">
                  <el-button slot="append" type="primary" @click="createAttr(item.detail.attrsVal, index)">添加</el-button>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="isBtn" class="mt10">
            <el-col :span="9" class="mr15">
              <el-form-item label="规格：">
                <el-input placeholder="请输入规格" v-model="attrsName" />
              </el-form-item>
            </el-col>
            <el-col :span="9" class="mr20">
              <el-form-item label="规格值：">
                <el-input v-model="attrsVal" placeholder="请输入规格值" />
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" @click="createAttrName">确定</el-button>
            </el-col>
            <el-col :span="2">
              <el-button @click="offAttrName">取消</el-button>
            </el-col>
          </el-col>
        </el-row>
        <el-button type="primary" icon="md-add" @click="addBtn" v-if="!isBtn" class="ml95 mt10">添加新规格</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button :loading="modal_loading" type="primary" @click="handleSubmit('formData')">确认</el-button>
      </div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import {
  listStoreProductRule,
  getStoreProductRule,
  delStoreProductRule,
  addStoreProductRule,
  updateStoreProductRule,
} from "@/api/business/storeProductRule";

export default {
  name: "StoreProductRule",
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品规则值(规格)表格数据
      storeProductRuleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: null,
        ruleValue: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ruleName: [
          { required: true, message: "规格名称不能为空", trigger: "blur" },
        ],
      },
      modal_loading: false,
      index: 1,
      formData: {
        ruleName: "",
        ruleValue: [],
      },
      attrsName: "",
      attrsVal: "",
      isBtn: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商品规则值(规格)列表 */
    getList() {
      this.loading = true;
      listStoreProductRule(this.queryParams).then((response) => {
        this.storeProductRuleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.formData = {
        ruleName: "",
        ruleValue: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.formData = {
        ruleName: "",
        ruleValue: [],
      }
      this.reset();
      this.open = true;
      this.title = "添加商品规则值(规格)";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getStoreProductRule(id).then((response) => {
        this.formData = response.data;
        this.open = true;
        this.title = "修改商品规则值(规格)";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(1);
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateStoreProductRule(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStoreProductRule(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {
          return delStoreProductRule(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/storeProductRule/export",
        {
          ...this.queryParams,
        },
        `storeProductRule_${new Date().getTime()}.xlsx`
      );
    },

    // 添加按钮
    addBtn() {
      this.isBtn = true;
    },
    // 提交
    handleSubmit(name) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.formData.ruleValue) {
            return this.$message.warning("请至少添加一条商品规格！");
          }
          if (this.formData.ruleValue.length === 0) {
            return this.$message.warning("请至少添加一条商品规格！");
          }
          this.modal_loading = true;

          setTimeout(() => {
            //   crudYxStoreProductRule
            //     .add(this.formData, this.ids)
            //     .then((res) => {
            //       setTimeout(() => {
            //         if (this.ids) {
            //           this.crud.status.edit = CRUD.STATUS.NORMAL;
            //           this.crud.editSuccessNotify();
            //         } else {
            //           this.crud.status.add = CRUD.STATUS.NORMAL;
            //           this.crud.addSuccessNotify();
            //         }

            //         this.crud.resetForm();
            //         this.crud.toQuery();
            //         this.modal_loading = false;
            //       }, 500);
            //       setTimeout(() => {
            //         this.clear();
            //       }, 600);
            //     })
            //     .catch((res) => {
            //       this.modal_loading = false;
            //       this.$message({
            //         message: res.msg,
            //         type: "error",
            //       });
            //     });
            if(this.formData.id != null){
              updateStoreProductRule(this.formData).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
            }else{
              addStoreProductRule(this.formData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
            }
            this.modal_loading = false
            return true
          }, 1200);
        } else {
          return false;
        }
      });
    },
    // 取消
    offAttrName() {
      this.isBtn = false;
    },
    // 删除
    handleRemove(index) {
      this.formData.ruleValue.splice(index, 1);
    },
    // 删除属性
    handleRemove2(item, index) {
      item.splice(index, 1);
    },
    // 添加规则名称
    createAttrName() {
      if (this.attrsName && this.attrsVal) {
        let data = {
          value: this.attrsName,
          detail: [this.attrsVal],
        };
        this.formData.ruleValue.push(data);
        var hash = {};
        this.formData.ruleValue = this.formData.ruleValue.reduce(function (
          item,
          next
        ) {
          /* eslint-disable */
          hash[next.value] ? "" : (hash[next.value] = true && item.push(next));
          return item;
        },
          []);
        this.attrsName = "";
        this.attrsVal = "";
        this.isBtn = false;
      } else {
        return this.$message.warning("请添加规格名称！");
      }
    },
    // 添加属性
    createAttr(num, idx) {
      if (num) {
        this.formData.ruleValue[idx].detail.push(num);
        var hash = {};
        this.formData.ruleValue[idx].detail = this.formData.ruleValue[
          idx
        ].detail.reduce(function (item, next) {
          hash[next] ? "" : (hash[next] = true && item.push(next));
          return item;
        }, []);
      } else {
        return this.$message.warning("请添加属性！");
      }
    },
  },
};
</script>
